package org.jeecg.modules.ca.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import org.jeecg.modules.ca.dto.CompanyDto;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenService {

	public String getToken(CompanyDto user) {
        String token="";
        token= JWT.create().withAudience(String.valueOf(user.getEnterpriseCode()))
                .sign(Algorithm.HMAC256(user.getEnterpriseName()));
        return token;
    }
	
	public String getEnterpriseCode(HttpServletRequest httpServletRequest) {
		String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
		if(token == null){
			return "";
		}
		String userId = JWT.decode(token).getAudience().get(0);
		return userId;
    }

	public String getByToken(String token) {
		try {
			if(token.isEmpty()){
				return "";
			}
			String userId = JWT.decode(token).getAudience().get(0);
			return userId;
		} catch (JWTDecodeException e) {
			e.printStackTrace();
			return  "";
		}
	}
}
